package model

import (
	"log"
	"time"

	"github.com/bwmarrin/snowflake"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"gorm.io/plugin/optimisticlock"
	"gorm.io/plugin/soft_delete"
)

type BaseModel struct {
	ID         int64                  `gorm:"primaryKey;comment:主键ID" json:"id"`
	CreateTime time.Time              `gorm:"type:timestamp;not null;default:CURRENT_TIMESTAMP;comment:创建时间" json:"createTime"`
	ModifyTime time.Time              `gorm:"type:timestamp;not null;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;comment:更新时间" json:"modifyTime"`
	CreatorId  int64                  `gorm:"comment:创建者ID" json:"creatorId"`
	ModifierId int64                  `gorm:"comment:更新者ID" json:"modifierId"`
	IsDeleted  soft_delete.DeletedAt  `gorm:"softDelete:flag"` // use `1` `0`
	Version    optimisticlock.Version `gorm:"column:version;type:bigint;default:1;comment:版本号" json:"-"`
}

// Insert 钩子
func (base *BaseModel) BeforeCreate(tx *gorm.DB) (err error) {
	node, err := snowflake.NewNode(1)
	if err != nil {
		return err
	}
	base.ID = node.Generate().Int64()

	// 修正：正确获取 Gin Context 中的值（主要是因为 Gin 的 Context.Keys 是私有字段，不能直接用 ctx.Value() 获取 ）
	if ginCtx, ok := tx.Statement.Context.(*gin.Context); ok {
		if userId, exists := ginCtx.Get("userId"); exists {
			if id, ok := userId.(int); ok { // 注意类型断言
				base.CreatorId = int64(id)
				base.ModifierId = int64(id)
				log.Printf("Successfully set creator_id to %d", id)
			}
		}
	}
	return
}
